package com.buddies.lottery.ui.withdraw;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.buddies.lottery.App;
import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseActivity;
import com.buddies.lottery.common.ConfigManager;
import com.buddies.lottery.data.bean.Bank;
import com.buddies.lottery.data.resp.WithdrawResponse;
import com.buddies.lottery.ui.help.HelpActivity;
import com.buddies.lottery.ui.wallet.bank.BankActivity;
import com.buddies.lottery.ui.wallet.pwd.UpdateWalletPwdActivity;
import com.buddies.lottery.ui.withdraw.record.WithdrawRecordActivity;
import com.buddies.lottery.utils.LotteryUtils;
import com.r0adkll.slidr.Slidr;

public class WithdrawActivity extends BaseActivity<WithdrawContract.Presenter> implements WithdrawContract.View {

    private static final int REQUEST_BIND_BANK = 1001;
    private TextView tvBindStatus;

    private Bank mBank;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private View btnPost;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Slidr.attach(this, App.getSlidrConfig());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_withdraw;
    }

    @Override
    protected void initView() {
        setUp();
        setTitle("我的收益");

        TextView btnWithRecord = (TextView) findViewById(R.id.tv_action);
        btnWithRecord.setVisibility(View.VISIBLE);
        btnWithRecord.setText("提现记录");
        btnWithRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WithdrawRecordActivity.launch(getActivity()); // 提现记录
            }
        });

        mSwipeRefreshLayout = findViewById(R.id.refresher);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                forceRefresh();
            }
        });

        tvBindStatus = findViewById(R.id.tv_bind_status);

        findViewById(R.id.btn_bind).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toBank();
            }
        });

        btnPost = findViewById(R.id.btn_post);
        btnPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ConfigManager.getInstance().isWalletPwdExist()) {
                    ToastUtils.showShort("未设置资金密码");
                    UpdateWalletPwdActivity.launch(getActivity());
                    return;
                } else if (mBank == null || !mBank.isValid()) {
                    ToastUtils.showShort("未绑定提现银行卡");
                    BankActivity.launch(getActivity(), REQUEST_BIND_BANK);
                    return;
                }

                View container = LayoutInflater.from(getActivity()).inflate(R.layout.item_withdraw_money, null);

                final EditText editText = (EditText) container.findViewById(R.id.et_money);
                editText.setFocusable(true);
                editText.setFocusableInTouchMode(true);
                editText.requestFocus();

                final EditText etPwd = (EditText) container.findViewById(R.id.et_pwd);

                AlertDialog dialog = new AlertDialog.Builder(getActivity())
                        .setTitle("提现信息")
                        .setView(container)
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String moneyText = editText.getText().toString();
                                if (TextUtils.isEmpty(moneyText)) {
                                    ToastUtils.showShort("请输入提现金额");
                                    return;
                                }

                                String pwd = etPwd.getText().toString();
                                if (TextUtils.isEmpty(pwd)) {
                                    ToastUtils.showShort(R.string.wallet_pwd_require);
                                    return;
                                }

                                int money = Integer.parseInt(moneyText);
                                if (money > ConfigManager.getInstance().getBalance()) {
                                    ToastUtils.showShort("输入金额大于可提现金额");
                                    return;
                                }

                                mPresenter.postWithdraw(money, EncryptUtils.encryptMD5ToString(pwd));
                                showProgressDialog("正在提交");
                            }
                        })
                        .setCancelable(false)
                        .create();
                dialog.setCanceledOnTouchOutside(false);
                dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialog) {
                        editText.post(new Runnable() {
                            @Override
                            public void run() {
                                KeyboardUtils.showSoftInput(editText);
                            }
                        });
                    }
                });
                dialog.show();
            }
        });

        findViewById(R.id.btn_help).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HelpActivity.launch(getActivity(), "提现帮助", getString(R.string.withdraw_tips));
            }
        });
    }

    private void toBank() {
        if (!ConfigManager.getInstance().isWalletPwdExist()) {
            UpdateWalletPwdActivity.launch(getActivity());
        } else {
            BankActivity.launch(getActivity(), REQUEST_BIND_BANK);
        }
    }

    @Override
    protected void initData() {
        onUpdateWallet();

        mPresenter = new WithdrawPresenter(this);

        forceRefresh();
    }

    private void forceRefresh() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(true);
                    mPresenter.loadWithdrawInfo();
                }
            });
        }
    }

    @Override
    public void onWithdrawInfoLoaded(WithdrawResponse response) {
        mBank = response.bank;

        onUpdateWallet();
        onUpdateBindStatus();
    }

    private void onUpdateWallet() {
        mSwipeRefreshLayout.setRefreshing(false);

        TextView tvAvailableMoney = findViewById(R.id.tv_available_money);
        TextView tvTodayMoney = findViewById(R.id.tv_today_money);
        TextView tvTotalMoney = findViewById(R.id.tv_total_money);

        tvAvailableMoney.setText(String.valueOf((int) ConfigManager.getInstance().getBalance()));
        tvTodayMoney.setText(LotteryUtils.formatMoney(ConfigManager.getInstance().getTodayWinMoney()));
        tvTotalMoney.setText(LotteryUtils.formatMoney(ConfigManager.getInstance().getWin()));

        float minMoney = ConfigManager.getInstance().getWithdrawMinMoney() - ConfigManager.getInstance().getBalance();
        btnPost.setEnabled(minMoney < 0);

        TextView tvRemind = findViewById(R.id.tv_remind);
        tvRemind.setVisibility(minMoney < 0 ? View.GONE : View.VISIBLE);
        tvRemind.setText(String.format("还差%s元可提现", LotteryUtils.formatMoney(minMoney)));
    }

    private void onUpdateBindStatus() {
        if (!ConfigManager.getInstance().isWalletPwdExist()) {
            tvBindStatus.setText("未设置资金密码");
        } else if (mBank == null || !mBank.isValid()) {
            tvBindStatus.setText("未绑定提现银行卡");
        } else {
            tvBindStatus.setText(String.format("%s %s", mBank.card_name, mBank.card_no.substring(mBank.card_no.length() - 4)));
        }
    }

    @Override
    public void onQrcodePostSuccess() {

    }

    @Override
    public void onWithdrawPostSuccess() {
        ToastUtils.showShort("已成功提交提现请求");
        hideProgressDialog();
        onUpdateWallet();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_BIND_BANK && resultCode == RESULT_OK && data != null) {
            mBank = (Bank) data.getSerializableExtra("bank");
            onUpdateBindStatus();
        }
    }

    public static void launch(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, WithdrawActivity.class);
        context.startActivity(intent);
    }

}
